package com.dyz.leetcode._02_string;

public class _8_myAtoi {
    public int myAtoi(String s) {
        int n  = s.length();
        if(n==0) {return 0;}

        char[] chars = s.toCharArray();

        //丢弃前导空格
        int i = 0;
        while(i<n && chars[i]==' '){
            i++;
        }
        // 2. 检查 + 和 - 是否存在
        int sign = 1;
        if (i<n && (chars[i] == '-' || chars[i] == '+')) {
            sign = chars[i] == '-' ? -1 : 1;
            i++;
        }

        //3 计算，并判断数字书否溢出
        int base = 0;
        while(i<n && chars[i]>='0' && chars[i]<='9'){
            //判断是否溢出
            // [-231, 231 - 1]--> 2147483647 ~ -2147483648
            if(sign==1 && (base>Integer.MAX_VALUE/10 || (base==Integer.MAX_VALUE/10 && chars[i]-'0'>7))){
                return Integer.MAX_VALUE;
            }

            if(sign==-1 && (base>Integer.MIN_VALUE/10*sign || base==Integer.MIN_VALUE/10*sign && chars[i]-'0'>8)){
                return Integer.MIN_VALUE;
            }

            base = base*10 +(chars[i]-'0');
            i++;
        }
        return base *sign;
    }
}
